package com.xiaobaibai.service.impl;

import com.xiaobaibai.bo.ShoppingCarRedisBo;
import com.xiaobaibai.bo.ShoppingCartVo;
import com.xiaobaibai.common.UserCommon;
import com.xiaobaibai.entity.Product;
import com.xiaobaibai.service.IProductService;
import com.xiaobaibai.service.IShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements IShoppingCartService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IProductService productService;

    @Override
    @Cacheable(value = "shoppingCart",key = "#root.methodName+'-'+#userId")
    public List<ShoppingCartVo> getShoppingCartByUserId(Integer userId) {
        List<ShoppingCarRedisBo> list=
                redisTemplate.opsForList().range(UserCommon.shoppingCart + userId, 0, -1);

        if(list==null)
            return null;

        List<ShoppingCartVo> result=new ArrayList<>(list.size());
        list.forEach(l->{
            Product product = productService.getProductById(l.getProductId());
            ShoppingCartVo shoppingCartVo = ShoppingCartVo.getInstance(product);
            shoppingCartVo.setCount(l.getCount());
            result.add(shoppingCartVo);
        });
        return result;
    }

    @Override
    @CacheEvict(value = "shoppingCart",key = "'getShoppingCartByUserId-'+#userId")
    public void addShoppingCart(List<ShoppingCarRedisBo> list,Integer userId) {
        redisTemplate.delete(UserCommon.shoppingCart+userId);
        redisTemplate.opsForList().leftPushAll(UserCommon.shoppingCart+userId,list);
    }

}
